import type { Ref, WritableComputedRef } from 'vue'
import { useEditorStore }  from '@/stores/modules'

interface IContainerRef extends Ref<HTMLElement> {
  key?: string
}

/**
 *
 * @param containerRef dom元素
 * @param data 已经注册的菜单组件数据
 */
export function useMenuDrag(
  containerRef: Ref<HTMLElement>,
  data: WritableComputedRef<Record<string, any>>
) {
  const editorStore = useEditorStore()
  
  let currentComponent: IContainerRef | null = null

  // 拖拽开始
  const dragenter = (e: any) => {
    // 移动到目标容器内,添加一个移动标识
    e.dataTransfer.dropEffect = 'copy'
  }
  // 拖拽结束
  const dragover = (e: any) => {
    e.preventDefault()
  }
  // 拖拽离开
  const dragleave = (e: any) => {
    e.dataTransfer.dropEffect = 'none'
  }
  // 拖拽放置
  const drop = (e: any) => {
    data.value = {
      ...data.value,
      blocks: [
        ...data.value.blocks,
        {
          top: e.offsetY,
          left: e.offsetX,
          zIndex: 1,
          key: currentComponent?.key,
          alignCenter: true,
          props: {},
          model: {}
        }
      ]
    }

    currentComponent = null
  }

  // 拖拽开始
  const headleDragStart = (e: MouseEvent, component: Ref<HTMLElement>) => {
    // 进入目标容器内,添加一个移动标识
    containerRef.value.addEventListener('dragenter', dragenter, false)
    // 经过目标容器  阻止默认动作以启用drop
    // 经过目标容器  阻止默认动作以启用drop
    containerRef.value.addEventListener('dragover', dragover, false)
    // 当拖动元素离开可放置目标节点， 添加一个禁用标识
    containerRef.value.addEventListener('dragleave', dragleave, false)
    // 将拖动的元素到所选择的放置目标节点中
    containerRef.value.addEventListener('drop', drop, false)
    currentComponent = component

    editorStore.events = 'start'
  }

  // 拖拽结束
  const handleDragEnd = () => {
    containerRef.value.removeEventListener('dragenter', dragenter, false)
    containerRef.value.removeEventListener('dragover', dragover, false)
    containerRef.value.removeEventListener('dragleave', dragleave, false)
    containerRef.value.removeEventListener('drop', drop, false)

    editorStore.events = 'end'
  }

  return {
    headleDragStart,
    handleDragEnd
  }
}
